const Router = require('koa-router')
const category = new Router()
const db = require('../untils/database')

category.get('/mailCategory',async(ctx)=>{
    let sql = `SELECT * FROM category_main`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})

category.post('/subCategory',async(ctx)=>{
    // console.log(ctx.request.body);
    let mainId = ctx.request.body.mainId
    let sql = `SELECT * FROM category_sub WHERE mainId = '${mainId}'`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})

category.post('/getGoodsListByCategorySubID',async(ctx)=>{
    let categorySubId = ctx.request.body.categorySubId //小类别
    let pageSize =  5 //每页显示数量
    let start = ctx.request.body.pageNum ? ((ctx.request.body.pageNum-1)*pageSize) : 0
    let sql = `SELECT id,productImg,productName,oldPrice,presentPrice FROM product WHERE subId = '${categorySubId}' limit ${start},${pageSize}`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            message: result,
            msg: 'success'
        }
    }else{
        ctx.body = {
            message: null,
            msg: 'successs'
        }
    }
})


module.exports = category;